package org.jeecg.modules.demo.advancesReceived.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.advancesReceived.entity.YxAdvancesReceived;
import org.jeecg.modules.demo.advancesReceived.service.IYxAdvancesReceivedService;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

 /**
 * @Description: yx_advances_received
 * @Author: jeecg-boot
 * @Date:   2021-12-16
 * @Version: V1.0
 */
@Api(tags="yx_advances_received")
@RestController
@RequestMapping("/advancesReceived/yxAdvancesReceived")
@Slf4j
public class YxAdvancesReceivedController extends JeecgController<YxAdvancesReceived, IYxAdvancesReceivedService> {
	@Autowired
	private IYxAdvancesReceivedService yxAdvancesReceivedService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private IPuBuyOrderService puBuyOrderService;

	 private static final String TITLE = "单据审核";




	 private String getMessage(String name,String date) {
		 String str ="由【"+name+"】于【"+date+"】发起的预付款单需要您的审核，请及时查看！";
		 return str;
	 }
	/**
	 * 分页列表查询
	 *
	 * @param yxAdvancesReceived
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "预付款单-分页列表查询")
	@ApiOperation(value="预付款单-分页列表查询", notes="预付款单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/advancesReceived/YxAdvancesReceivedList")
	public Result<?> queryPageList(YxAdvancesReceived yxAdvancesReceived,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<YxAdvancesReceived> queryWrapper = QueryGenerator.initQueryWrapper(yxAdvancesReceived, req.getParameterMap());
			queryWrapper.ne("SHANCHU",1);
			queryWrapper.eq("DOCUMENT_TYPE",0);
			Page<YxAdvancesReceived> page = new Page<YxAdvancesReceived>(pageNo, pageSize);
			IPage<YxAdvancesReceived> pageList = yxAdvancesReceivedService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	 /**
	  * 分页列表查询
	  *
	  * @param yxAdvancesReceived
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "期初预付款单-分页列表查询")
	 @ApiOperation(value="期初预付款单-分页列表查询", notes="期初预付款单-分页列表查询")
	 @GetMapping(value = "/queryQCPageList")
	 @PermissionData(pageComponent="yunxiao/advancesReceived/periodYxAdvancesReceivedList")
	 public Result<?> queryQCPageList(YxAdvancesReceived yxAdvancesReceived,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 try{
			 QueryWrapper<YxAdvancesReceived> queryWrapper = QueryGenerator.initQueryWrapper(yxAdvancesReceived, req.getParameterMap());
			 queryWrapper.ne("SHANCHU",1);
			 queryWrapper.eq("DOCUMENT_TYPE",1);
			 Page<YxAdvancesReceived> page = new Page<YxAdvancesReceived>(pageNo, pageSize);
			 IPage<YxAdvancesReceived> pageList = yxAdvancesReceivedService.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(300,"网络故障！");
		 }
	 }
	 /**
	  *   添加
	  *
	  * @param yxAdvancesReceived
	  * @return
	  */
	 @AutoLog(value = "期初预付款单-添加")
	 @ApiOperation(value="期初预付款单-添加", notes="期初预付款单-添加")
	 @PostMapping(value = "/addQC")
	 public Result<?> addQC(@RequestBody YxAdvancesReceived yxAdvancesReceived,HttpServletRequest req) {
		 try{
			 String tenantId = req.getHeader("tenant-id");
			 String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			 yxAdvancesReceived.setSupAmount(yxAdvancesReceived.getAmount());
			 yxAdvancesReceived.setShanchu(0);
			 yxAdvancesReceived.setDeadStatus(0);
			 yxAdvancesReceived.setTos(2);
			 yxAdvancesReceived.setCreateTime(new Date());
			 yxAdvancesReceived.setDocumentType(1);
			 String str = yxAdvancesReceivedService.getMaxCode();
			 Map<String,String> map = new HashMap<>();
			 map.put("maxCode",str==null?null:str);
			 String name = precode+"QCYF_";
			 String resultCode = generateOddUtil.createCode(map,name);
			 yxAdvancesReceived.setReceiptNumber(resultCode);
			 yxAdvancesReceivedService.save(yxAdvancesReceived);
			 LoginUser user = sysBaseAPI.getUserById(yxAdvancesReceived.getPoStaff());
			 TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
			 templateMessageDTO.setFromUser("管理员");
			 templateMessageDTO.setToUser(yxAdvancesReceived.getSaleman()+",");
			 templateMessageDTO.setTitle(TITLE);
			 templateMessageDTO.setTemplateCode("order");
			 Map<String, String> templateParam = new HashMap<>();
			 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 String date= simpleDateFormat.format(new Date());
			 templateParam.put("ts_date",date);
			 templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
			 templateParam.put("checkOrder",yxAdvancesReceived.getReceiptNumber());
			 templateParam.put("cd_url","/advancesReceived/yxAdvancesReceived/list");
			 templateMessageDTO.setTemplateParam(templateParam);
			 sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

			 return Result.OK("成功!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }
	/**
	 *   添加
	 *
	 * @param yxAdvancesReceived
	 * @return
	 */
	@AutoLog(value = "预付款单-添加")
	@ApiOperation(value="预付款单-添加", notes="预付款单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody YxAdvancesReceived yxAdvancesReceived,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			yxAdvancesReceived.setSupAmount(yxAdvancesReceived.getAmount());
			yxAdvancesReceived.setShanchu(0);
			yxAdvancesReceived.setDeadStatus(0);
			yxAdvancesReceived.setTos(2);
			yxAdvancesReceived.setCreateTime(new Date());
			yxAdvancesReceived.setDocumentType(0);
			String str = yxAdvancesReceivedService.getMaxCode();
			Map<String,String> map = new HashMap<>();
			if(str==null){
				map.put("maxCode",null);
			}else{
				map.put("maxCode",str);
			}
			String name = precode+"YF_";
			String resultCode = generateOddUtil.createCode(map,name);
			yxAdvancesReceived.setReceiptNumber(resultCode);
			yxAdvancesReceivedService.save(yxAdvancesReceived);


			LoginUser user = sysBaseAPI.getUserById(yxAdvancesReceived.getPoStaff());
			TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
			templateMessageDTO.setFromUser("管理员");
			templateMessageDTO.setToUser(yxAdvancesReceived.getSaleman()+",");
			templateMessageDTO.setTitle(TITLE);
			templateMessageDTO.setTemplateCode("order");
			Map<String, String> templateParam = new HashMap<>();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			String date= simpleDateFormat.format(new Date());
			templateParam.put("ts_date",date);
			templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
			templateParam.put("checkOrder",yxAdvancesReceived.getReceiptNumber());
			templateParam.put("cd_url","/advancesReceived/yxAdvancesReceived/list");
			templateMessageDTO.setTemplateParam(templateParam);
			sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

			return Result.OK("成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}
	 /**
	  *  退款
	  *
	  * @param yxAdvancesReceived
	  * @return
	  */
	 @AutoLog(value = "预付款单-退款")
	 @ApiOperation(value="预付款单-退款", notes="预付款单-退款")
	 @PostMapping(value = "/refund")
	 public Result<?> refund(@RequestBody YxAdvancesReceived yxAdvancesReceived) {
		 try{
			// 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(yxAdvancesReceived.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(yxAdvancesReceived.getDeadStatus()==0){
				 return Result.error(300,"单据未审核！");
			 }
			 if(yxAdvancesReceived.getSupAmount().doubleValue()<yxAdvancesReceived.getAmount().doubleValue()){
				 return Result.error(300,"预付款已被使用，无法退款！");
			 }
			 yxAdvancesReceived.setDeadStatus(9);
			 yxAdvancesReceived.setShTime(new Date());
			 yxAdvancesReceivedService.updateById(yxAdvancesReceived);
			 return Result.OK("退款成功!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误!");
		 }
	 }
	 /**
	  *  审核
	  *
	  * @param yxAdvancesReceived
	  * @return
	  */
	 @AutoLog(value = "预付款单-审核")
	 @ApiOperation(value="预付款单-审核", notes="预付款单-审核")
	 @PostMapping(value = "/checkYS")
	 public Result<?> checkYS(@RequestBody YxAdvancesReceived yxAdvancesReceived) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			if(!sysUser.getId().equals(yxAdvancesReceived.getSaleman())){
				return Result.error(500,"您不是当前单据的指定审核人！");
			}
			if(yxAdvancesReceived.getDeadStatus()==1){
				return Result.error(300,"单据已审核，请勿重复审核！");
			}

			yxAdvancesReceived.setDeadStatus(1);
			yxAdvancesReceived.setShTime(new Date());
			yxAdvancesReceivedService.updateById(yxAdvancesReceived);
			return Result.OK("审核成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误!");
		}
	 }
	 /**
	  *  弃审
	  *
	  * @param yxAdvancesReceived
	  * @return
	  */
	 @AutoLog(value = "预付款单-弃审")
	 @ApiOperation(value="预付款单-弃审", notes="预付款单-弃审")
	 @PostMapping(value = "/unCheckYs")
	 public Result<?> unCheckYs(@RequestBody YxAdvancesReceived yxAdvancesReceived) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(yxAdvancesReceived.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(yxAdvancesReceived.getDeadStatus()==0){
				 return Result.error(300,"请先审核单据！");
			 }

			 if(yxAdvancesReceived.getSupAmount().doubleValue()<yxAdvancesReceived.getAmount().doubleValue()){
				 return Result.error(300,"预付款已被使用，无法弃审！");
			 }
			 yxAdvancesReceived.setShTime(null);
			 yxAdvancesReceived.setDeadStatus(0);
			 yxAdvancesReceivedService.updateById(yxAdvancesReceived);
			 return Result.OK("弃审成功!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误!");
		 }
	 }

	/**
	 *  编辑
	 *
	 * @param yxAdvancesReceived
	 * @return
	 */
	@AutoLog(value = "预付款单-编辑")
	@ApiOperation(value="预付款单-编辑", notes="预付款单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody YxAdvancesReceived yxAdvancesReceived) {
		try{
//			yxAdvancesReceived.setCreateTime(new Date());
			yxAdvancesReceivedService.updateById(yxAdvancesReceived);
			return Result.OK("编辑成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "预付款单-通过id删除")
	@ApiOperation(value="预付款单-通过id删除", notes="预付款单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			YxAdvancesReceived advancesReceived = yxAdvancesReceivedService.getById(id);
			if(advancesReceived.getDeadStatus()==1){
				return Result.error(300,"单据已审核，无法删除！");
			}
			if(advancesReceived.getDeadStatus()==9){
				return Result.error(300,"单据已退回，无法删除！");
			}
			advancesReceived.setShanchu(1);
			yxAdvancesReceivedService.removeById(id);
			return Result.OK("删除成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "预付款单-批量删除")
	@ApiOperation(value="预付款单-批量删除", notes="预付款单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.yxAdvancesReceivedService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "预付款单-通过id查询")
	@ApiOperation(value="预付款单-通过id查询", notes="预付款单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		YxAdvancesReceived yxAdvancesReceived = yxAdvancesReceivedService.getById(id);
		if(yxAdvancesReceived==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(yxAdvancesReceived);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param yxAdvancesReceived
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YxAdvancesReceived yxAdvancesReceived) {
        return super.exportXls(request, yxAdvancesReceived, YxAdvancesReceived.class, "yx_advances_received");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YxAdvancesReceived.class);
    }


	//获取预收款剩余金额
	//发票单页面查询预收款总金额、剩余、已使用金额
	@GetMapping(value = "/getYcgBytradecode")
	public String getYcgBytradecode(@RequestParam(name = "tradecode", required = true) String tradecode) {
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			Map<String,Double> stringDoubleMap = this.yxAdvancesReceivedService.getYcgBytradecode(tradecode);
			//map.put("yszje",stringDoubleMap.get("YSKJE"));
			map.put("syje",stringDoubleMap.get("SYJE"));
			//map.put("useje",stringDoubleMap.get("USEJE"));
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}

	}


}
